package com.ateam.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ateam.biz.CompaniesBiz;
import com.ateam.pojo.Companies;
import com.ateam.pojo.Users;

/**
 * @author WuYuan 公司
 */

@Controller
public class CompaniesController {
	@Resource(name = "companiesBiz")
	private CompaniesBiz companiesBiz;

	// 新用户注册公司
	@ResponseBody
	@RequestMapping("registercompany.do")
	public boolean userLogin(Companies company, HttpSession session, HttpServletRequest request) {
		if (session.getAttribute("currentUser") != null) {
			if (session.getAttribute("currentCompany") != null) {
				Users users = (Users) session.getAttribute("currentUser");
				if (0 != companiesBiz.addCompany(company, users)) {
					session.setAttribute("currentCompany", company);
					return true;
				} else
					return false;
			} else
				return false;
		} else
			return false;
	}

	// 新用户选择想加入的公司
	@RequestMapping("getallcompanies.do")
	public String getallcompanies(HttpSession session, HttpServletRequest request) {
		if (session.getAttribute("currentUser") != null) {
			if (session.getAttribute("currentCompany") != null) {
				Users user = (Users) session.getAttribute("currentUser");
				if (user.getCompanyid() == 1) {
					List<Companies> companies = companiesBiz.getAllCompanies();
					request.setAttribute("companies", companies);
					return "companieslist";
				} else
					return "index";
			} else
				return "index";
		} else
			return "index";
	}

	// 新用户申请加入所选公司
	@RequestMapping("applycompany.do")
	public String applycompany(String companyid, HttpSession session, HttpServletRequest request) {
		if (session.getAttribute("currentUser") != null) {
			if (session.getAttribute("currentCompany") != null) {
				Users user = (Users) session.getAttribute("currentUser");
				if (user.getCompanyid() == 1) {
					if (0 != companiesBiz.updateApplyCompany(Integer.parseInt(companyid), user.getUserid())) {
						return "loginsuccess";
					} else
						return "index";
				} else
					return "index";
			} else
				return "index";
		} else
			return "index";
	}

	// 公司创建人通过申请
	@ResponseBody
	@RequestMapping("passapplyer.do")
	public boolean passapplyer(String userid, HttpSession session, HttpServletRequest request) {
		if (session.getAttribute("currentUser") != null) {
			if (session.getAttribute("currentCompany") != null) {
				Companies currentCompany = (Companies) session.getAttribute("currentCompany");
				if (0 != companiesBiz.updatePassApply(currentCompany.getCompanyid(), Integer.parseInt(userid))) {
					return true;
				}
				return false;
			} else
				return false;
		} else
			return false;
	}

}
